package org.anddev.andengine.entity.particle.modifier;

import org.anddev.andengine.engine.handler.physics.PhysicsHandler;
import org.anddev.andengine.entity.particle.Particle;

/**
 * Bounce a particle (by reversing velocity) when it hits given bounds
 * 
 * @author adam
 *
 */

public class BounceOnBoundsModifier implements IParticleModifier {

	public final float mBoundsMaxX;
	public final float mBoundsMaxY;

	public final float mBoundsMinX;
	public final float mBoundsMinY;

	
	public BounceOnBoundsModifier (float pBoundsMaxX, float pBoundsMaxY) {
		mBoundsMaxX = pBoundsMaxX;
		mBoundsMaxY = pBoundsMaxY;
		
		mBoundsMinX = 0;
		mBoundsMinY = 0;
	}
	
	public BounceOnBoundsModifier (float pBoundsMinX, float pBoundsMinY, float pBoundsMaxX, float pBoundsMaxY) {
		mBoundsMaxX = pBoundsMaxX;
		mBoundsMaxY = pBoundsMaxY;
		
		mBoundsMinX = pBoundsMinX;
		mBoundsMinY = pBoundsMinY;

	}
	
	@Override
	public void onUpdateParticle(Particle pParticle) {
		final float pX = pParticle.getX();
		final float pY = pParticle.getY();
		final PhysicsHandler pPhys = pParticle.getPhysicsHandler();
		float tX = pX;
		float tY = pY;
		if (pX < mBoundsMinX) {
			tX = mBoundsMinX;
			pPhys.setVelocityX(pPhys.getVelocityX() * -1);
			this.onBounce(pParticle);
		} else if (pX > mBoundsMaxX) {
			tX = mBoundsMaxX;
			pPhys.setVelocityX(pPhys.getVelocityX() * -1);
			this.onBounce(pParticle);
		}
		if (pParticle.getY() < mBoundsMinY) {
			tY = mBoundsMinY;
			pPhys.setVelocityY(pPhys.getVelocityY() * -1);
			this.onBounce(pParticle);
		} else if (pParticle.getY() > mBoundsMaxY) {
			tY = mBoundsMaxY;
			pPhys.setVelocityY(pPhys.getVelocityY() * -1);
			this.onBounce(pParticle);
		}
		if (tX != pX || tY != pY) pParticle.setPosition(tX, tY);
	}

	protected void onBounce(Particle pParticle) {
		// TODO Auto-generated method stub		
	}

	@Override
	public void onInitializeParticle(Particle pParticle) {
		// nothing
	}

}
